package com.yyx.up.producer.io;

import com.yyx.up.common.bean.Data;
import com.yyx.up.common.bean.DataIn;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Description: 本地文件数据输入
 * @Author: yyx
 * @Create: 2023/4/10 11:24
 * @Version: 8
 */
public class LocalFileDataIn implements DataIn {
    private BufferedReader reader = null;//可以读取一行数据流
    private BufferedReader reader2 = null;

    public LocalFileDataIn(String path, String path2) {
        setPath(path,path2);
    }

    @Override
    public void setPath(String path, String path2) {
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));//字符流转换为字节流
            reader2 = new BufferedReader(new InputStreamReader(new FileInputStream(path2),"UTF-8"));
        } catch (UnsupportedEncodingException | FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object read() throws IOException {
        return null;
    }

    /**
     * 读取数据，返回数据集合
     * @param clazz
     * @param <T>
     * @return
     * @throws IOException
     */
    @Override
    public <T extends Data> List<T> read(Class<T> clazz) throws IOException {
        List<T> ts = new ArrayList<>();
        try {
            // 从数据文件中读取所有的数据
            String line = null;
            while ((line = reader.readLine()) != null){//读到数据的时候
                // 将数据转换为指定类型的对象，封装为集合返回
                T t = clazz.newInstance();//反射
                t.setValue(line);
                ts.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ts;
    }
    @Override
    public <T extends Data> List<T> read2(Class<T> clazz) throws IOException {
        List<T> ts = new ArrayList<T>();
        try {
            // 从数据文件中读取所有的数据
            String line = null;
            while ((line = reader2.readLine()) != null){//读到数据的时候
                // 将数据转换为指定类型的对象，封装为集合返回
                T t = clazz.newInstance();//反射
                t.setValue(line);
                ts.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ts;
    }

    /**
     * 关闭资源
     * @throws IOException
     */
    public void close() throws IOException {
        if(reader != null){
            reader.close();
        }
    }
}
